package com.chouxiaozi.dbroute.proxy;

import com.chouxiaozi.dbroute.db.DynamicDataSourceEntity;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.text.SimpleDateFormat;
import java.util.Date;

public class OrderServiceCglibProxy implements MethodInterceptor {

    private SimpleDateFormat yearFormat = new SimpleDateFormat("yyyy");

    public Object getInstance(Class<?> clazz){
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(clazz);
        enhancer.setCallback(this);
        return enhancer.create();
    }

    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        before(objects[0]);
        Object obj = methodProxy.invokeSuper(o, objects);
        after();
        return obj;
    }

    private void before(Object target) {
        try {
            Long time = (Long) target.getClass().getMethod("getCreateTime").invoke(target);
            Integer dbRouter = Integer.valueOf(yearFormat.format(new Date(time)));
            System.out.println("静态代理类自动分配到【DB_" +  dbRouter + "】数据源处理数据" );
            DynamicDataSourceEntity.set(dbRouter);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private void after() {
        DynamicDataSourceEntity.restore();
    }
}
